import { ref, type Ref } from 'vue';
import type { Editor as EditorType } from 'tinymce/tinymce';
import * as Docx from 'docx-preview';

export function useWordImporter(editorRef: Ref<EditorType | null>) {
  const importWordUploadRef = ref<HTMLInputElement | null>(null);
  // docx-preview 没有提供直接返回 html 的方法，所以用创建 dom 接收 html 的方法“曲线救国”
  const renderHtmlAsync = async (wordFile: File) => {
    const importWordUploadContainerDom = document.createElement('div');
    await Docx.renderAsync(wordFile, importWordUploadContainerDom, undefined, {
      // 取消宽高限制，不然会固定一个页面大小，展示效果不好
      ignoreHeight: true,
      ignoreWidth: true,
    });
    // 给包裹 img 的父元素添加 text-align:center 样式（仅当图片本应居中）
    importWordUploadContainerDom.querySelectorAll('img').forEach((img) => {
      const parent = img.parentElement;
      if (parent) {
        // 简单判断：如果 parent 是 P 或 DIV 且没有 text-align，手动添加
        img.style.setProperty('max-width', '100%', 'important');
        img.style.setProperty('height', 'auto', 'important');
        parent.style.setProperty('max-width', '100%', 'important');
        parent.style.setProperty('height', 'auto', 'important');
        console.log(parent, img);
      }
    });
    // 获取 style 标签
    const wordStyleContent = Array.from(
      importWordUploadContainerDom.querySelectorAll('style'),
    )
      .map((dom) => dom.outerHTML)
      .join('');
    // 去除 word 的纸页容器
    const wordHtmlContent = Array.from(
      importWordUploadContainerDom.querySelectorAll('section.docx'),
    )
      .map((dom) => dom.innerHTML)
      .join('');

    return wordStyleContent + wordHtmlContent;
  };
  const handleWordFileUpload = async (e: Event) => {
    const wordFile = (e.target as HTMLInputElement).files?.[0];
    if (!wordFile) return;
    // 将上传文件的 input value 置空，否则会出现第二次上传相同文件的时候不回调的问题
    importWordUploadRef.value = null;
    const wordHtmlContent = await renderHtmlAsync(wordFile);

    // 将导入的 word 内容追加到富文本内容中
    editorRef.value?.setContent(
      editorRef.value?.getContent() + wordHtmlContent,
    );
  };

  const triggerImportWord = () => {
    importWordUploadRef.value?.click();
  };

  return {
    importWordUploadRef, // Expose ref for the parent component to bind in template
    handleWordFileUpload,
    triggerImportWord,
  };
}
